package com.project.sevice;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.util.Enumeration;

/**
 * @Author(王思翰)
 * @Description(类的描述)
 * @Date(创建时间) 2021/7/20 10:25
 */
@Controller
public class EmServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        req.setCharacterEncoding("utf-8");
//        resp.setContentType("text/html;charset=utf-8");
//
//        EmployeeBean bean = new EmployeeBean();
//        this.fullBean(bean, req);
//
//        resp.getWriter().println(bean);
//        resp.getWriter().println("<hr>");
//        //将java对象转换为json格式
//        ObjectMapper om=new ObjectMapper();
//        //提供日期类型的支持
//        om.registerModule(new JavaTimeModule());
//        String josonStr=om.writeValueAsString(bean);
//        resp.getWriter().println(josonStr);
//
//        resp.getWriter().println("<hr>");
//        om.writeValue(resp.getWriter(),bean);
//    }

    private void fullBean(Object bean, HttpServletRequest req) {
        //得到请求参数的表单名
        Enumeration<String> em = req.getParameterNames();
        Class beanClass = bean.getClass();


        while (em.hasMoreElements()) {//判断是否有下一个元素
            //取出下一个元素
            String str = em.nextElement();
            Object value = req.getParameter(str);

            try {
                //得到属性对象
                Field field = beanClass.getDeclaredField(str);
                field.setAccessible(true);

                if (field.getType() == String.class) {
                    //得到属性对象
                    field.set(bean, value);
                } else if (field.getType() == int.class || field.getType() == Integer.class) {
                    field.set(bean, Integer.parseInt((String) value));
                } else if (field.getType() == LocalDate.class) {
                    field.set(bean, LocalDate.parse((String) value));
                } else if (field.getType() == String[].class) {
                    field.set(bean, req.getParameterValues(str));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
